package com.zxc.project.handler;

import com.zxc.project.base.BaseResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zxc.project.exception.GlobalExceptionEnum;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public BaseResponseEntity<String> exceptionHandler(HttpServletRequest request, Exception e){
        log.error("全局异常", e);
        if (e instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
            //多个错误，取第一个
            FieldError error = fieldErrors.get(0);
            String msg = error.getDefaultMessage();
            return BaseResponseEntity.fail(msg, GlobalExceptionEnum.PARAM_ERROR);
        }else {
            return BaseResponseEntity.fail("error");
        }
    }
}
